package com.jerry.base.io.file;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.*;

/**
 * Created with IntelliJ IDEA
 * User: Jerry
 * Date: 2024/1/27
 * Time: 14:37
 * Description:
 */
@Slf4j
public class BufferedFileCopy {

    /**
     * 以字符为单位的拷贝
     *
     * @throws IOException
     */
    @Test
    public void copy() throws IOException {
        String filePath = "src/main/resources/io/Buffered.txt";
        String copyPath = "src/main/resources/io/Buffered_copy.txt";

        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
             BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(copyPath))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        }
        log.info("拷贝完毕！");
    }

    /**
     * 以字节为单位的拷贝
     *
     * @throws IOException
     */
    @Test
    public void copy2() throws IOException {
        String filePath = "src/main/resources/io/girl.jpg";
        String copyPath = "src/main/resources/io/girl_buffered_copy.jpg";

        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(copyPath))) {
            byte[] bytes = new byte[1024];
            int lenth;
            ;
            while ((lenth = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, lenth);
            }
        }
        log.info("拷贝完毕！");
    }
}
